/**
 * 签到记录controller
 */
'use strict';

var _ = require('underscore');
var moment = require('moment');
var async = require("async");
var response = require('./response');
var config = require('../conf/config');
var coordiateUtil = require('../components/util/coordinate');
var db = require('../conf/db.js');
var errorCode = config.errorCode;



exports.getById = function(req, res){
     var user = req.session.user;
     var SignIn = db.model(user.tenant, 'SignIn');
     var Coordinate = db.model(user.tenant, 'Coordinate');
     var Timetable = db.model(user.tenant, 'Timetable');
     var id = req.params.id;

    async.waterfall([
        function(callback){
            SignIn.find({_id : id, userId : user.id}).exec(function (err, signIn) {
                callback(err, signIn[0]);
            });
        }, function(signIn, callback){
            async.parallel([function(_callback){
                Coordinate.findById(signIn.coordinateId, function(err, coordinate){
                    _callback(err, coordinate);
                });
            }, function(_callback){
                Timetable.findById(signIn.timetableId, function(err, timetable){
                    _callback(err, timetable);
                });
            }], function(err, result){
                var signInObj = signIn.toObject();
                signInObj.coordinate = result[0];
                signInObj.timetable = result[1];
                callback(err, signInObj);
            });
        }], function(err, result){
            if (err) {
                console.error('异常信息为：%s', JSON.stringify(err));
                response.error(res, config.errorCode.databaseError);
            } else {
                response.data(res, result);
            }
    });
};


exports.query = function(req, res){
    var user = req.session.user;
    var start = moment(req.params.start).toDate();
    var end = moment(req.params.end).toDate();
    var SignIn = db.model(user.tenant, 'SignIn');

    SignIn.find({userId : user.id, signInTime : {$gt : start,$lte : end}}).exec(function (err, signIns) {
        if (err) {
            console.error('异常信息为：%s', JSON.stringify(err));
            response.error(res, config.errorCode.databaseError);
        } else {
            var groupSignIns = {};

            // 分组
            _.each(signIns, function(signIn){
                var signInStr = moment(signIn.signInTime).format('YYYYMMDD');

                if (groupSignIns[signInStr]) {
                    groupSignIns[signInStr].push(signIn);
                } else {
                    groupSignIns[signInStr] = [signIn];
                }
            });

            // 排序
            for (var timeKey in groupSignIns) {
                groupSignIns[timeKey] = _.sortBy(groupSignIns[timeKey], function(signIn){
                    return signIn.signInTime;
                });
            }


            response.data(res, groupSignIns);
        }
    });
};

exports.queryAll = function(req, res){
    var page = req.query.page;
    var size = req.query.size;
    var name = req.query.userName;
    var condition = name ? {userName : new RegExp("^.*" + name + ".*$", 'i')} : {};
    var SignIn = db.model(req.session.user.tenant, 'SignIn');

    SignIn.find(condition).skip(page * size).limit(size).sort({'signInTime' : 'asc'}).exec(function (err, signIns) {
        if (err) {
            console.error('异常信息为：%s', JSON.stringify(err));
            response.error(res, config.errorCode.databaseError);
        } else {
            response.data(res, signIns);
        }
    });
};

exports.queryAuditCount = function(req, res){
    var user = req.session.user;
    var SignIn = db.model(user.tenant, 'SignIn');

    SignIn.count({approver : user.id}, function (err, count) {
        if (err) {
            console.error('异常信息为：%s', JSON.stringify(err));
            response.error(res, config.errorCode.databaseError);
        } else {
            response.data(res, count);
        }
    });
};

exports.queryAudit = function(req, res){
    var user = req.session.user;
    var SignIn = db.model(user.tenant, 'SignIn');

    SignIn.find({approver : user.id}).sort({'signInTime' : 'asc'}).exec(function (err, signIns) {
        if (err) {
            console.error('异常信息为：%s', JSON.stringify(err));
            response.error(res, config.errorCode.databaseError);
        } else {
            response.data(res, signIns);
        }
    });
};

exports.audit = function(req, res){
    var user = req.session.user;
    var ids = req.body.ids;
    var SignIn = db.model(user.tenant, 'SignIn');

    SignIn.update({_id : {$in : ids}}, {$set : {isPass : true}},{multi: true}, function(err, count){
        if (err) {
            console.error('异常信息为：%s', JSON.stringify(err));
            response.error(res, config.errorCode.databaseError);
        } else {
            response.success(res);
        }
    });
};

exports.causeDescription = function(req, res){
    var user = req.session.user;
    var SignIn = db.model(user.tenant, 'SignIn');
    SignIn.update({_id: req.body.id}, {$set : {description : req.body.causeDescription, approver : user.id}}, function(err, count){
        if (err) {
            console.error('异常信息为：%s', JSON.stringify(err));
            response.error(res, config.errorCode.databaseError);
        } else {
            response.success(res);
        }
    });

};

exports.signIn = function(req, res){
    var user = req.session.user;
    var SignIn = db.model(user.tenant, 'SignIn');
    var Coordinate = db.model(user.tenant, 'Coordinate');
    var Timetable = db.model(user.tenant, 'Timetable');
    var signIn = new SignIn(req.body);
    signIn.userId = user.id;
    signIn.userName = user.userName;

    console.info(req.body);

    async.parallel([function(callback){
        Timetable.find({isEnabled : true}).exec(function(err, timetable){
            callback(err, timetable[0]);
        })
    }, function(callback){
        Coordinate.find({isEnabled : true}).exec(function(err, coordinates){
            callback(err, coordinates);
        });
    }], function(err, result){
        var timetable = result[0];
        var coordinates = result[1];

        if (err) {
            console.error('异常信息为：%s', JSON.stringify(err));
            response.error(res, config.errorCode.databaseError);
        } else {
            var local = '';
            _.each(coordinates, function(coordinate){
                var distance = coordiateUtil.getDistance(
                    {x:coordinate.longitude, y: coordinate.latitude}, 
                    {x:signIn.longitude, y:signIn.latitude});
                 console.info(distance);
                if (distance <= coordinate.scope) {
                    signIn.distance = distance;
                    signIn.coordinateId = coordinate._id;
                    local = signIn.local;
                    return false;
                }
            });

            if (signIn.distance || signIn.distance == 0) {
                signIn.timetableId = timetable._id;
                signIn.save(function(err, signIn){
                    if (err) {
                        console.error('异常信息为：%s', JSON.stringify(err));
                        response.error(res, config.errorCode.databaseError);
                    } else {
                        signIn = signIn.toObject();
                        signIn.local = local;
                        response.data(res, signIn);
                    }
                });
            } else {
               response.error(res, config.errorCode.signInDistanceError);
            }
        }
    });
    
};


